package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.exception.SrbException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.result.Result;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.entity.vo.DictVO;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author Atguigu
 * @since 2023-03-25
 */
@RestController
@RequestMapping("/admin/core/dict")
//@CrossOrigin
@Api("数据字典管理")
public class AdminDictController {
    @Resource
    DictService dictService;


    @ApiOperation("导入数据字典")
    @PostMapping("/import")
    public Result importDicts(MultipartFile file){
        dictService.importDicts(file);
        return Result.ok().message("文件上传成功！");
    }

    @ApiOperation("导出数据字典")
    @GetMapping("/export")
    public void exportDicts(HttpServletResponse response){
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据字典"+new DateTime().toString("yyyy-MM-dd-HH-mm-ss"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //查询数据
            List<DictVO> dictVOList = dictService.list().stream().map(dict -> {
                DictVO dictVo = new DictVO();
                BeanUtils.copyProperties(dict, dictVo);
                return dictVo;
            }).collect(Collectors.toList());
            EasyExcel.write(response.getOutputStream())
                    .sheet()
                    .head(DictVO.class)
                    .doWrite(dictVOList);
        } catch (Exception e) {
            throw new SrbException(ResponseEnum.EXPORT_DATA_ERROR);
        }
    }

    @ApiOperation("根据父id获取所有字典数据")
    @GetMapping("/list/{pid}")
    public Result parent(
            @PathVariable("pid") String pid
    ){
        List<Dict> dictList = dictService.list(pid);
        return Result.ok().data("list", dictList);
    }

    @ApiOperation("根据id删除行")
    @DeleteMapping("/{id}")
    public Result delete(
            @PathVariable("id") String id
    ){
        //判断该数据字典是否有下一级
        Assert.assertNotTrue(dictService.hasChildren(id), ResponseEnum.HAS_CHILDREN_ERROR);
        Assert.assertTrue(dictService.removeById(id), ResponseEnum.ERROR);
        return Result.ok().message("删除成功");
    }

    @ApiOperation("新增数据字典")
    @PostMapping("/save")
    public Result save(
            @RequestBody Dict dict
    ){
        boolean b = dictService.save(dict);
        Assert.assertTrue(b, ResponseEnum.INSERT_ERROR);
        return Result.ok().message("新增成功");
    }

    @ApiOperation("根据id获取字典对象")
    @GetMapping("/{id}")
    public Result getDictById(
            @PathVariable("id") String id
    ){
        Dict dict = dictService.getById(id);
        return Result.ok().data("data", dict);
    }

    @ApiOperation("根据Id更新dict对象")
    @PutMapping("/update")
    @CacheEvict(value = "srb:dicts", key = "#dict.parentId")
    public Result update(
            @RequestBody Dict dict
    ){
        boolean b = dictService.updateById(dict);
        Assert.assertTrue(b, ResponseEnum.UPDATE_ERROR);
        return Result.ok().message("更新");
    }
}